package www.sofn.com.security.handle;


import cn.hutool.core.util.ObjectUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import www.sofn.com.constant.Constants;
import www.sofn.com.domain.R;
import www.sofn.com.security.domain.vo.TokenInfoVO;
import www.sofn.com.security.service.TokenService;
import www.sofn.com.utils.ServletUtils;

import java.io.IOException;

@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Resource
    private TokenService tokenService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        final TokenInfoVO tokenInfo = tokenService.getTokenInfo(request);
        if (ObjectUtil.isNotNull(tokenInfo)) {
            final String tokenId = tokenInfo.getTokenId();
            redisTemplate.delete(Constants.PERSONAL_CACHE_PREFIX + tokenInfo.getUsername());
            tokenService.delToken(tokenId);
        }
        ServletUtils.responseWriterJson(R.ok("退出登陆成功！"), response);
    }
}
